<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2019/3/7
 * Time: 13:42
 */

namespace app\api\controller;

use app\common\controller\Api;
use app\common\model\Wallet as WalletModel;
use app\common\model\WalletRecord;
use think\Db;
use think\helper\Hash;
use think\Request;
use app\api\Service\WalletService;
use app\api\Service\WebsocketService;
use app\common\model\WalletLog;
use app\common\model\WallertMultiple;


class Wallet extends Api
{
    protected $noNeedLogin = ['resetextractnum'];
    protected $noNeedRight = '*';
    protected $userWallet;
    protected $websocket;

    public function __construct(Request $request = null)
    {
        $this->websocket   = new WebsocketService();
        parent::__construct($request);
        $this->userWallet = WalletModel::where('user_id',$this->auth->id)->field('*')->find();

    }

    public function index()
    {
        $userInfo = $this->auth->getUserinfo();
        $this->success('', [$userInfo['wallet']]);
    }

    public function resetextractnum()
    {
        WalletModel::where('extract_num','<',5)->update(['extract_num'=>5]);
    }

    public function tixian(Request $request)
    {

        if( $request->isPost() ){
            $money  = $request->post('money');
            $userInfo = $this->auth->getUserinfo();
            $pwd = $request->post('password');
            $wallet = WalletModel::where('user_id',$userInfo['id'])->field('*')->find();

//            if( $userInfo['group_id'] == 1 ){
//                $this->error('该账户不允许出款！');
//            }

            if( !$wallet['name'] || !$wallet['idcard'] ){
                $this->error('请先绑定银行卡！');
            }
            if( $money < 100 ){
                $this->error('最低提现金额100元！');
            }

//            if( $wallet['extract_num'] <= 0 ){
//                $this->error('今日5次提现机会已用完！');
//            }

            if( $wallet['pay_password'] != $this->auth->getEncryptPassword($pwd,$wallet['salt']) ){
                $this->error('密码输入错误！');
            }

            if ( $wallet['money'] < $money ){
                $this->error('可提现金额有误！');
            }
            //计算当前流水
//            $water = WallertMultiple::where('user_id',$this->auth->id)->order('id','desc')->limit(1)->find();
//            if( $water && $water['surpluswate'] > 0 ){
//                $this->error('流水不足，当前还需￥'. $water['surpluswate'] .'流水');
//            }
            
            $res = WalletService::tixian($money);
            if( $res['code'] == 200 ){
                $messageData = [
                    'username'  => $this->auth->username,
                    'money'     => $money,
                    'type'      => 'tixian'
                ];
                $this->websocket->message($messageData);
                $this->success('提现成功,剩余次数'.($wallet['extract_num']-1).'次');
            }else{
                $this->error($res['msg']);
            }
        }

    }

    /**
     * 绑定银行卡号
     */
    public function bindBack(Request $request)
    {
        if( $request->isPost() ){
            $name = $request->post('name');
            $idcard = $request->post('idcard');
            $backtag = $request->post('tag');

            if( !$name || !$idcard || !$backtag ){
                $this->error('信息填写不完整！');
            }

            if( luhm($idcard) == false ){
                $this->error('银行卡号错误！');
            }
            $wallet = WalletModel::where('user_id',$this->auth->id)->find();
            if( $wallet['name'] && $wallet['idcard'] && $wallet['back_tag'] ){
                $this->error('您已绑定过银行卡！');
            }
            if( WalletModel::where('idcard',$idcard)->count() > 0 ){
                $this->error('该银行卡已被绑定！');
            }


            $wallet->name       = $name;
            $wallet->idcard     = $idcard;
            $wallet->back_tag   = $backtag;
            $wallet->save();
            $this->success('绑定成功！');
        }
    }

    /**
     * 修改提现密码
     * @param Request $request
     */
    public function updatePwd(Request $request)
    {
        if( $request->isPost() ){
            $pwd = $request->post('password'); //原始密码
            $newpwd = $request->post('newpassword'); //新密码
            $repwd = $request->post('repassword'); //确认密码

            if( $this->userWallet['pay_password'] != $this->auth->getEncryptPassword($pwd,$this->userWallet['salt']) ){
                $this->error('原密码输入错误！');
            }
            if( !preg_match("/^\d{6}$/",$newpwd) ){
                $this->error('请输入6位数字！');
            }
            if( $newpwd != $repwd ){
                $this->error('两次密码输入不一致！');
            }
            WalletModel::where('user_id',$this->auth->id)->update([
                'pay_password' => $this->auth->getEncryptPassword($newpwd,$this->userWallet['salt'])
            ]);
            $this->success('修改成功！');
        }
    }

    /**
     * $type 1 后台充值 2提现
     * 充值记录
     */
    public function records(Request $request)
    {
        $type = $request->get('type');
        if( $type == 1 ){
            $typeArr = [1,7,8];
        }elseif( $type == 2 ){
            $typeArr = [2];
        }

        $begin = $request->get('begin') ? strtotime($request->get('begin')) : strtotime(date('Y-m-d'));
        $end   = $request->get('end') ? strtotime($request->get('end')) : time();

        $page = request()->get('page') ? : 1 ;
        $pageNum = request()->get('page_num') ? : 30 ;
        $total = WalletRecord::with(['user'=>function($query){
            $query->field('id,username');
        }])
            ->where('user_id',$this->auth->id)
            ->whereIn('type',$typeArr)
            ->whereBetween('createtime',[$begin,$end])
            ->field('id,record_sn,pay_time,pay_status,user_id,money')
            ->count();

        $records = WalletRecord::with(['user'=>function($query){
            $query->field('id,username');
        }])
            ->where('user_id',$this->auth->id)
            ->whereIn('type',$typeArr)
            ->whereBetween('createtime',[$begin,$end])
            ->field('id,record_sn,pay_time,pay_status,user_id,money,type')
            ->limit($pageNum)->page($page)->order('createtime','desc')->select();


        foreach ($records as $k=>$v){
            $records[$k]['pay_time']    = date('Y-m-d H:i:s',$v['pay_time']);
            if( $v['pay_status'] == 1 ){
                $records[$k]['pay_status'] = '已到账';
            }elseif( $v['pay_status'] == 0 ){
                $records[$k]['pay_status'] = '待审核';
            }elseif( $v['pay_status'] == -1 ){
                $records[$k]['pay_status'] = '失败';
            }else{
                $records[$k]['pay_status'] = '未知错误!';
            }
        }

        $this->success('成功',['total'=>$total,'current_page'=>$page,'data'=>$records]);
    }

    //盈亏统计
    public function profit(Request $request)
    {
        $starttime  = $request->get('begin') ? strtotime($request->get('begin')) : strtotime(date('Y-m-d'));
        $endtime    = $request->get('end') ? strtotime($request->get('end')) : time();
        //盈亏计算公式：中奖-投注+活动+返点
        $lists = WalletRecord::where('createtime', 'between time', [$starttime, $endtime])
            ->where('user_id',$this->auth->id)
            ->where('pay_status',1)
            ->field('SUM(money) as nums,type,pay_status')
            ->group('type')
            ->select();//投注

        $recharge = 0;
        $zhongjiang = 0;
        $give = 0;
        $bets = 0;
        $tixian = 0;
        $fandian = 0;
        foreach ( $lists as $k=>$v ){
            if( $v['type'] == 4 ){
                $zhongjiang += $v['nums'];
            }
            if( $v['type'] == 5 ){
                $give += $v['nums'];
            }
            if( $v['type'] == 3 ){
                $bets += $v['nums'];
            }
            if( $v['type'] == 2 ){
                $tixian += $v['nums'];
            }
            if( $v['type'] == 1 || $v['type'] == 7 || $v['type'] == 8){
                $recharge += $v['nums'];
            }
            if( $v['type'] == 6 ){
                $fandian += $v['nums'];
            }
        }
        $grprofit = substr(sprintf("%.3f",$zhongjiang-$bets+$give),0,-1);//个人
        $data = [
            'bets'  => substr(sprintf("%.3f",$bets),0,-1),//下注
            'zhongjiang'    => substr(sprintf("%.3f",$zhongjiang),0,-1),//中奖
            'give'  => substr(sprintf("%.3f",$give),0,-1),//活动礼金
            'recharge'  => substr(sprintf("%.3f",$recharge),0,-1),//充值
            'tixian'    => substr(sprintf("%.3f",$tixian),0,-1),//提现
            'fandian'    => substr(sprintf("%.3f",$fandian),0,-1),//返点
            'grprofit'   => $grprofit,//个人盈利
        ];
        $this->success('成功',$data);
    }
    public function recharge(Request $request)
    {
        $money = $request->param('money');
        $type  = $request->param('type');//充值类型
        $banktype = $request->param('banktype');
        $user_id  = $this->auth->id;
        $walletService = new WalletService();
        $res = $walletService->recharge($user_id,$money,$type,$banktype);
        if( $type == 'unionpay' ){
            $this->success('成功',$res);
        }elseif( $type == 'alipay' ){
            $this->success('成功',$res);
        }else{
            $this->success('成功',$res);
        }
    }

}